using BuildingBlocks.Abstractions.Permissions;
using Grpc.Net.Client;
using PermissionCenter.Grpc;

namespace Catalog.Infrastructure.GrpcClients
{
    public class PermissionBindingServiceGrpcClient: IPermissionBindingServiceClient
    {
        private readonly PermissionBindingService.PermissionBindingServiceClient _client;

        public PermissionBindingServiceGrpcClient(string permissionBindingUrl)
        {
            // 本地开发信任自签名证书
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            };

            // gRPC Channel for PermissionBindingService
            var bindingChannel = GrpcChannel.ForAddress(permissionBindingUrl, new GrpcChannelOptions
            {
                HttpHandler = handler
            });
            _client = new PermissionBindingService.PermissionBindingServiceClient(bindingChannel);
        }

        public async Task<IReadOnlyCollection<PermissionBindingDto>> GetBindingsAsync(string serviceName, CancellationToken ct = default)
        {
            var resp = await _client.GetBindingsAsync(new GetBindingsRequest { ServiceName = serviceName }, cancellationToken: ct);

            return resp.Bindings.Select(b => new PermissionBindingDto
            {
                permissionKey = b.PermissionKey,
                resourceId = b.ResourceId,
            }).ToList();
        }
    }
}
